package com.feng.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.feng.chat.common.Common;
import com.feng.chat.dto.*;
import com.feng.chat.entity.*;
import com.feng.chat.mapper.*;
import com.feng.chat.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feng.chat.utils.GetUserUtil;
import com.feng.chat.vo.ApplyDeclineVO;
import com.feng.chat.vo.EditRemarkVO;
import com.feng.chat.vo.PaginateVO;
import com.feng.chat.vo.RowsVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户好友关系表 服务实现类
 * </p>
 *
 * @author dyf
 * @since 2022-05-31
 */
@Service
public class ContactServiceImpl extends ServiceImpl<ContactMapper, Contact> implements IContactService {
    @Autowired
    private TalkRecordsMapper talkRecordsMapper;

    @Autowired
    private TalkSessionMapper talkSessionMapper;

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private ContactApplyMapper contactApplyMapper;

    /**
     * 获取未读的好友申请消息数量
     *
     * @param id
     * @return
     */
    @Override
    public Result GetApplyUnreadNum(Integer id) {
        QueryWrapper<TalkRecords> talkRecordsQueryWrapper = new QueryWrapper<>();
        talkRecordsQueryWrapper.eq("receiver_id", id).eq("msg_type", 7).eq("is_read", 0);
        long count = talkRecordsMapper.selectCount(talkRecordsQueryWrapper);
        Map<String, Long> map = new HashMap<>();
        map.put("unread_num", count);
        return Result.success(map);
    }

    /**
     * 获取好友列表
     * @param id
     * @return
     */
    @Override
    public Result friendList(Integer id) {
        QueryWrapper<Contact> contactQueryWrapper = new QueryWrapper<>();
        contactQueryWrapper.eq("user_id", id).eq("status", 2).orderByAsc("updated_at");
        List<Contact> contactList = list(contactQueryWrapper);

        List<ContactListDTO> contactListDTOS = new ArrayList<>();
        contactListDTOS = contactList.stream().map(item -> {
            ContactListDTO contactListDTO = new ContactListDTO();
            contactListDTO.setFriend_remark(item.getRemark());
            Users users = usersMapper.selectById(item.getFriendId());
            contactListDTO.setAvatar(users.getAvatar());
            contactListDTO.setGender(users.getGender());
            contactListDTO.setNickname(users.getNickName());
            contactListDTO.setId(users.getId());
            contactListDTO.setMotto(users.getMotto());

            //TODO 判断用户是否在线
            contactListDTO.setIs_online(GetUserUtil.isOnLine(users.getId()));

            return contactListDTO;
        }).collect(Collectors.toList());


        return Result.success(contactListDTOS);
    }

    /**
     * 获取好友申请信息
     *
     * @param id
     * @param page
     * @param page_size
     * @return
     */
    @Override
    public Result applyRecords(Integer id, Integer page, Integer page_size) {

        PageHelper.startPage(page, page_size);
        QueryWrapper<ContactApply> contactApplyQueryWrapper = new QueryWrapper<>();
        contactApplyQueryWrapper.eq("friend_id", id).eq("operation", 0);
        List<ContactApply> contactApplyList = contactApplyMapper.selectList(contactApplyQueryWrapper);
        List<RowsVO> rowsVOS = new ArrayList<>();
        rowsVOS = contactApplyList.stream().map(item -> {
            RowsVO rowsVO = new RowsVO();
            rowsVO.setCreated_at(item.getCreatedAt().format(DateTimeFormatter.ofPattern(Common.LOCALDATETIME_FORMATER)));
            rowsVO.setId(item.getId());
            rowsVO.setFriend_id(id);
            rowsVO.setUser_id(item.getUserId());
            rowsVO.setRemark(item.getRemark());
            Users users = usersMapper.selectById(item.getUserId());

            rowsVO.setAvatar(users.getAvatar());
            rowsVO.setNickname(users.getNickName());
            return rowsVO;
        }).collect(Collectors.toList());

        PageInfo<RowsVO> rowsVOPageInfo = new PageInfo<>(rowsVOS);
        PaginateVO paginateVO = new PaginateVO();
        paginateVO.setPage(page);
        paginateVO.setSize(page_size);
        paginateVO.setTotal(rowsVOPageInfo.getTotal());

        ApplyRecordsDTO applyRecordsDTO = new ApplyRecordsDTO();
        applyRecordsDTO.setPaginate(paginateVO);
        applyRecordsDTO.setRows(rowsVOPageInfo.getList());
        return Result.success(applyRecordsDTO);
    }

    /**
     * 通过手机号查询用户
     *
     * @param mobile
     * @return
     */
    @Override
    public Result search(String mobile) {
        QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
        usersQueryWrapper.eq("mobile", mobile);
        Users users = usersMapper.selectOne(usersQueryWrapper);
        SearchDTO searchDTO = new SearchDTO();
        searchDTO.setAvatar(users.getAvatar());
        searchDTO.setId(users.getId());
        searchDTO.setGender(users.getGender());
        searchDTO.setMobile(users.getMobile());
        searchDTO.setMotto(users.getMotto());
        searchDTO.setNickname(users.getNickName());
        return Result.success(searchDTO);
    }

    /**
     * 通过id查询用户及好友状态
     * @param id
     * @param user_id
     * @return
     */
    @Override
    public Result detail(Integer id, Integer user_id) {
        DetailDTO detailDTO = new DetailDTO();

        Users users = usersMapper.selectById(user_id);
        detailDTO.setAvatar(users.getAvatar());
        detailDTO.setGender(users.getGender());
        detailDTO.setMobile(users.getMobile());
        detailDTO.setMotto(users.getMotto());
        detailDTO.setNickname(users.getNickName());
        detailDTO.setId(users.getId());
        if (id == user_id) {
            return Result.success(detailDTO);
        }
        QueryWrapper<Contact> contactQueryWrapper = new QueryWrapper<>();
        contactQueryWrapper.eq("user_id", id).eq("friend_id", user_id);
        Contact contact = getOne(contactQueryWrapper);

        if (contact!=null){
            detailDTO.setFriend_status(contact.getStatus());
        }else {
            detailDTO.setFriend_status(1);
        }


        QueryWrapper<ContactApply> contactApplyQueryWrapper = new QueryWrapper<>();
        contactApplyQueryWrapper.eq("user_id", id).eq("friend_id", user_id).ne("operation",1).orderByDesc("created_at").last("limit 1");
        ContactApply contactApply = contactApplyMapper.selectOne(contactApplyQueryWrapper);

        if (contactApply == null || contactApply.getOperation() == 2) {
            detailDTO.setFriend_apply(0);
        } else if (contactApply != null && contactApply.getOperation() == 0) {
            detailDTO.setFriend_apply(1);
        }
        return Result.success(detailDTO);
    }

    /**
     * 发送好友申请
     *
     * @param contactApply
     * @return
     */
    @Override
    public Result applyCreate(ContactApply contactApply) {
        int save = contactApplyMapper.insert(contactApply);
        //TODO
        TalkRecords talkRecords = new TalkRecords();
        talkRecords.setTalkType(1);
        talkRecords.setMsgType(7);
        ;
        talkRecords.setUserId(contactApply.getUserId());
        talkRecords.setReceiverId(contactApply.getFriendId());
        talkRecords.setContent(contactApply.getRemark());
        int save1 = talkRecordsMapper.insert(talkRecords);
        if (save==1 && save1==1) {
            return Result.success();
        }
        return Result.fail();
    }

    /**
     * 拒绝好友申请
     *
     * @param applyDeclineVO
     * @return
     */
    @Override
    public Result applyDecline(ApplyDeclineVO applyDeclineVO) {
        UpdateWrapper<ContactApply> contactApplyUpdateWrapper = new UpdateWrapper<>();
        contactApplyUpdateWrapper.eq("id", applyDeclineVO.getApply_id()).set("operation", 2).set("operation_notes", applyDeclineVO.getRemark());
        contactApplyMapper.update(null,contactApplyUpdateWrapper);
        return Result.success();
    }

    /**
     * 同意好友申请
     * @param applyDeclineVO
     * @return
     */
    @Override
    public Result applyAccept(Integer id, ApplyDeclineVO applyDeclineVO) {
        UpdateWrapper<ContactApply> contactApplyUpdateWrapper = new UpdateWrapper<>();
        contactApplyUpdateWrapper.eq("id", applyDeclineVO.getApply_id()).set("operation", 1).set("operation_notes", applyDeclineVO.getRemark());
        contactApplyMapper.update(null,contactApplyUpdateWrapper);

        ContactApply contactApply = contactApplyMapper.selectById(applyDeclineVO.getApply_id());

        QueryWrapper<Contact> contactQueryWrapper = new QueryWrapper<>();
        contactQueryWrapper.eq("user_id", contactApply.getFriendId()).eq("friend_id", contactApply.getUserId());

        Contact contact = getOne(contactQueryWrapper);


        QueryWrapper<Contact> contactQueryWrapper1 = new QueryWrapper<>();
        contactQueryWrapper1.eq("user_id", contactApply.getUserId()).eq("friend_id", contactApply.getFriendId());

        Contact contact1 = getOne(contactQueryWrapper1);

        Users users = usersMapper.selectById(id);
        if (contact != null && contact1 != null) {
            contact.setStatus(2);
            contact.setRemark(applyDeclineVO.getRemark());
            boolean update = updateById(contact);

            contact1.setStatus(2);

            contact1.setRemark(users.getNickName());
            boolean update1 = updateById(contact1);
        } else {
            Contact contactAdd = new Contact();
            contactAdd.setUserId(id);
            contactAdd.setFriendId(contactApply.getUserId());
            contactAdd.setStatus(2);
            contactAdd.setRemark(applyDeclineVO.getRemark());

            Contact contactAdd1 = new Contact();
            contactAdd1.setUserId(contactApply.getUserId());
            contactAdd1.setFriendId(id);
            contactAdd1.setStatus(2);
            contactAdd1.setRemark(users.getNickName());

            ArrayList<Contact> contacts = new ArrayList<>();
            contacts.add(contactAdd);
            contacts.add(contactAdd1);
            boolean b = saveBatch(contacts);
        }

        TalkRecords talkRecords = new TalkRecords();
        talkRecords.setContent("你们已成为好友，可以开始聊天咯!");
        talkRecords.setReceiverId(id);
        talkRecords.setUserId(contactApply.getUserId());
        talkRecords.setTalkType(1);
        talkRecords.setMsgType(0); //系统文本消息

        talkRecordsMapper.insert(talkRecords);

        return Result.success();
    }

    /**
     * 删除好友
     *
     * @param friend_id
     * @param userId
     * @return
     */
    @Override
    public Result delete(Integer friend_id, Integer userId) {
        QueryWrapper<Contact> contactQueryWrapper = new QueryWrapper<>();
        contactQueryWrapper.eq("user_id", userId).eq("friend_id", friend_id);
        Contact contact = getOne(contactQueryWrapper);
        if (contact == null || contact.getStatus() == 1) {
            return Result.fail("你们还不是好友哦");
        }


        UpdateWrapper<Contact> contactUpdateWrapper = new UpdateWrapper<>();
        contactUpdateWrapper.eq("user_id", userId).eq("friend_id", friend_id).set("status", 1);
        boolean update = update(contactUpdateWrapper);
        UpdateWrapper<Contact> contactUpdateWrapper1 = new UpdateWrapper<>();
        contactUpdateWrapper1.eq("user_id", friend_id).eq("friend_id", userId).set("status", 1);
        boolean update1 = update(contactUpdateWrapper1);

        UpdateWrapper<TalkSession> talkSessionUpdateWrapper = new UpdateWrapper<>();
        talkSessionUpdateWrapper.eq("user_id", friend_id).eq("receiver_id", userId).set("is_delete", 1);
        int update2 = talkSessionMapper.update(null,talkSessionUpdateWrapper);

        TalkRecords talkRecords = new TalkRecords();
        talkRecords.setTalkType(1);
        talkRecords.setMsgType(0);
        talkRecords.setUserId(userId);
        talkRecords.setReceiverId(friend_id);
        talkRecords.setContent("你与对方已经解除了好友关系！！！");

        talkRecordsMapper.insert(talkRecords);
        return Result.success();
    }

    /**
     * 修改好友备注
     * @param editRemarkVO
     * @param userId
     * @return
     */
    @Override
    public Result editRemark(EditRemarkVO editRemarkVO, Integer userId) {
        UpdateWrapper<Contact> contactUpdateWrapper = new UpdateWrapper<>();
        contactUpdateWrapper.eq("user_id",userId).eq("friend_id",editRemarkVO.getFriend_id()).set("remark",editRemarkVO.getRemarks());
        boolean update = update(contactUpdateWrapper);
        return Result.success();
    }


}
